/* eslint-disable no-unreachable */
export const isTest = function() {
  return process.env.VUE_APP_API_ENV === 'test' || process.env.VUE_APP_API_ENV === 'stag'
}

export const checkBrowser = function() {
  if (!(window && window.navigator)) {
    return {}
  }
  const u = window.navigator.userAgent
  return {
    trident: u.indexOf('Trident') > -1, // IE内核
    presto: u.indexOf('Presto') > -1, // opera内核
    webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
    android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, // android终端
    iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
    iPad: u.indexOf('iPad') > -1, // 是否iPad
    webApp: u.indexOf('Safari') === -1, // 是否web应该程序，没有头部与底部
    weixin: u.indexOf('MicroMessenger') > -1, // 是否微信 （2015-01-22新增）
    qq: u.match(/\sQQ/i) === ' qq', // 是否QQ
  }
}

export const getQueryVariable = function(variable) {
  // #ifdef H5
  const query = window.location.search.substring(1)
  const vars = query.split('&')
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=')
    if (pair[0] === variable) {
      return pair[1]
    }
  }
  return false
  /*
   * #endif
   * #ifndef H5
   */
  return false
  // #endif
}


export function delParam(url, paramKey) {
  if (!url || url.indexOf('?') === -1) {
    return url
  }
  const urlParam = url.substring(url.indexOf('?') + 1)   // 页面参数
  const beforeUrl = url.substr(0, url.indexOf('?'))   // 页面主地址（参数之前地址）
  let nextUrl = ''
  const arr = []
  if (urlParam !== '') {
    const urlParamArr = urlParam.split('&') // 将参数按照&符分成数组
    for (let i = 0; i < urlParamArr.length; i++) {
      const paramArr = urlParamArr[i].split('=') // 将参数键，值拆开
      // 如果键雨要删除的不一致，则加入到参数中
      if (paramArr[0] !== paramKey) {
        arr.push(urlParamArr[i])
      }
    }
  }
  if (arr.length > 0) {
    nextUrl = '?' + arr.join('&')
  }
  return beforeUrl + nextUrl
}

export function parseParams(url, params) {
  let uri = url
  const paramsArray = []
  Object.keys(params).forEach((key) => params[key] && paramsArray.push(`${key}=${params[key]}`))
  if (uri.search(/\?/) === -1) {
    uri += `?${paramsArray.join('&')}`
  } else {
    uri += `&${paramsArray.join('&')}`
  }
  const urlLastStr = uri.substr(uri.length - 1, 1)
  const lastUrl = urlLastStr === '?' ? uri.substring(0, uri.length - 1) : uri
  return lastUrl
}

// #ifdef H5
/**
 * 存储sessionStorage
 */
export const setSessionStore = (name, content) => {
  if (!name) {
    return
  }
  let contentStr = content
  if (typeof content !== 'string') {
    contentStr = JSON.stringify(content)
  }
  window.sessionStorage.setItem(name, contentStr)
}

/**
 * 获取sessionStorage
 */
export const getSessionStore = (name) => {
  if (!name) {
    return
  }
  return window.sessionStorage.getItem(name)
}

/**
 * 删除sessionStorage
 */
export const removeSessionStore = (name) => {
  if (!name) {
    return
  }
  window.sessionStorage.removeItem(name)
}
// #endif

export function httpErrorInterceptor401() {
  uni.removeStorageSync('tokenid')
  uni.removeStorageSync('userCenterData')
  if (getApp().globalData.isFromApp) {
    window.postMessage(JSON.stringify({ msgType: 'onLogin' }))
  } else {
    const page = getCurrentPages()
    let url = page[page.length - 1].route
    const { options } = page[page.length - 1]
    for (const i in options) {
      if (url.indexOf('?') > -1) {
        url += `&${i}=${options[i]}`
      } else {
        url += `?${i}=${options[i]}`
      }
    }
    url = '/' + url
    uni.setStorageSync('fromUrl', url)
    // uni.navigateTo({
    //   url: '/pages/main/pages/login/index',
    // })
    
    uni.navigateTo({
      url: '/pages/main/pages/login/pre-index',
    })
  }
}


export function jumpToLogin() {
  httpErrorInterceptor401()
}

// 登录成功的页面跳转
export function loginGoPage() {
  const fromurl = uni.getStorageSync('fromurl')
  if (fromurl) {
    uni.removeStorageSync('fromurl')
    uni.reLaunch({
      url: fromurl,
    })
  } else {
    uni.reLaunch({
      url: '/pages/main/pages/tab-bar/user',
    })
  }
}